"use server";
import {
  UpdateProfileFormData,
  UpdateProfilePasswordFormData,
  UpdateProfilePasswordSchema,
  UpdateProfileSchema,
} from "@/schemas/profile";
import prisma from "@/lib/prisma";
import bcrypt from "bcryptjs";
import { getUserByMobile, getUserByUserId } from "@/data/user";
import { getTranslations } from "next-intl/server";
import { User } from "../../generated/prisma";
export const UpdateProfileAction = async (values: UpdateProfileFormData) => {
  const tZod = await getTranslations("zod");
  const validatedFields = UpdateProfileSchema(tZod).safeParse(values);
  if (!validatedFields.success) return { error: "Invalid fields" };
  if (values.mobile) {
    const user = await getUserByMobile(values.mobile, { password: true });
    if (user && user.mobile) {
      return { error: "Mobile number already exists" };
    }
  }
  const isUpdated = await prisma.user.update({
    where: {
      id: values.id,
    },
    data: {
      name: values.name,
      first_name: values.first_name,
      last_name: values.last_name,
      image: values.image,
      address: values.address,
      region: values.region,
      mobile: values.mobile?.trim() === "" ? null : values.mobile,
    },
  });
  if (!isUpdated) return { error: "Error updating user" };
  return {
    success: "Profile updated successfully",
  };
};

export const UpdateProfilePasswordAction = async (
  values: UpdateProfilePasswordFormData
) => {
  const tZod = await getTranslations("zod");
  const validatedFields = UpdateProfilePasswordSchema(tZod).safeParse(values);
  if (!validatedFields.success) return { error: "Invalid fields" };
  const user = await getUserByUserId(values.id);
  if (!user) return { error: "User not found" };
  const password = await bcrypt.hash(values.password, 10);
  const new_password = await bcrypt.hash(values.new_password, 10);

  if (user.password && (await bcrypt.compare(password, user.password))) {
    return { error: "Incorrect password" };
  }
  const isUpdated = await prisma.user.update({
    where: {
      id: values.id,
    },
    data: {
      password: new_password,
    },
  });
  if (!isUpdated) return { error: "Error updating password" };
  return {
    success: "Password updated successfully",
  };
};

export const getProfileAction = async ({ id }: { id: string }) => {
  if (!id) return null;
  const user = await getUserByUserId(id, { password: true }) as Omit<User, "password">;
  if (!user) return null;
  return user;
};